package com.myjob.serviceImpl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myjob.config.Constants;
import com.myjob.entity.Company;
import com.myjob.entity.Hr;
import com.myjob.entity.User;
import com.myjob.enums.CompanyEnums;
import com.myjob.enums.RedisEnums;
import com.myjob.enums.UserEnums;
import com.myjob.exception.DBOptionException;
import com.myjob.mapper.CompanyMapper;
import com.myjob.response.Result;
import com.myjob.service.CompanyService;
import com.myjob.service.HrService;
import com.myjob.service.UserService;
import com.myjob.utils.RedisUtil;
import com.myjob.utils.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.rmi.runtime.Log;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Chen Yuan
 * @create 2021-01-23  15:10
 */
@Service
@Slf4j
public class CompanyServiceImpl implements CompanyService {
	@Autowired
	private CompanyMapper companyMapper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserService userService;
	@Autowired
	private HrService hrService;

	/**
	 * 查询企业信息
	 * @param currentPage 当前页面
	 * @param pageSize 每页大小
	 * @param companyName 企业名称
	 * @param financingSituation 融资情况
	 * @param companySize 企业规模
	 * @param enterprisesType 企业类型
	 * @param memberLevel 会员等级
	 * @param companyStatus 企业状态
	 * @return 封装好的结果对象
	 */
	@Override
	public Result selectCompanies(Integer currentPage, Integer pageSize,String searchValue,
	                              String companyName, String financingSituation,
	                              String companySize, String enterprisesType,
	                              String memberLevel, List<String> companyStatus, String companyAddress) {
		Result result = null;
		QueryWrapper<Company> wrapper = new QueryWrapper<>();

		if (UtilValidate.isNotEmpty(searchValue)) {
			wrapper.and(w -> w.like("company_name", searchValue).
								or().like("industry", searchValue).
								or().like("introduction", searchValue).
								or().like("enterprises_type", searchValue));
		}

		if (UtilValidate.isNotEmpty(companyName)){
			wrapper.like("company_name", companyName);
		}
		if (UtilValidate.isNotEmpty(financingSituation)){
			wrapper.eq("financing_situation",financingSituation);
		}
		if (UtilValidate.isNotEmpty(companySize) && !companySize.contains("-1")){
			List<String> list = Arrays.asList(companySize.split(","));
			wrapper.in("company_size", list);
		}
		if (UtilValidate.isNotEmpty(enterprisesType)){
			wrapper.eq("enterprises_type",enterprisesType);
		}
		if (UtilValidate.isNotEmpty(memberLevel)){
			wrapper.eq("member_level", memberLevel);
		}
		if (UtilValidate.isNotEmpty(companyAddress)) {
			wrapper.like("company_address", companyAddress);
		}
		if (UtilValidate.isNotEmpty(companyStatus)) {
			wrapper.in("company_status", companyStatus);
		}
		wrapper.orderByDesc("in_date");
		Page<Company> page = null;
		if (UtilValidate.isEmpty(pageSize)){
			page = new Page<>(currentPage, Constants.getPageSize());
		}else {
			page = new Page<>(currentPage, pageSize);
		}
		IPage<Company> companies = companyMapper.selectPage(page, wrapper);
		result = Result.succeed(companies);
		return result;
	}

	@Override
	public Company selectOneCompany(String companyId) {
		Company company = null;
		if (UtilValidate.isNotEmpty(companyId)){
			QueryWrapper<Company> wrapper = new QueryWrapper<>();
			wrapper.eq("company_id",companyId);
			company = companyMapper.selectOne(wrapper);
		}
		return company;
	}


	/**
	 * 添加企业
	 * @param company 企业信息
	 * @return 影响行数
	 */
	@Override
	public int addCompany(Company company) {
		if (UtilValidate.isEmpty(company)){
			return -1;
		}
		// 随机插入默认的图标
		String defaultLogoPath = "http://8.140.25.39/images/defaultConpany/logo-"+ (int) (1 + Math.random() * 10) +".jpg";
		company.setLogo(defaultLogoPath);
		company.setMemberLevel(CompanyEnums.MEMBER_LEVEL.free.getValue());
		company.setCompanyStatus(UserEnums.ACCOUNT_STATUS.normal.getValue());
		company.setMemberEndDate(DateUtil.offsetDay(new Date(), 1));
		return companyMapper.insert(company);
	}

	/**
	 * 修改企业
	 * @param company 企业信息
	 * @return 影响行数
	 */
	@Override
	@Transactional(rollbackFor = {DBOptionException.class, RuntimeException.class})
	public int updateCompany(Company company) {
		if (UtilValidate.isEmpty(company)){
			return -1;
		}
		String companyLogo = (String) redisUtil.get(RedisEnums.KEY_IN_REDIS.COMPANY_LOGO.getValue() + company.getCompanyId() + ".png");
		String companyPhoto = (String) redisUtil.get(RedisEnums.KEY_IN_REDIS.COMPANY_PHOTO.getValue() + company.getCompanyId() + ".png");

		if (UtilValidate.isNotEmpty(companyLogo)) {
			company.setLogo(companyLogo);
		}
		if (UtilValidate.isNotEmpty(companyPhoto)) {
			company.setCompanyPhoto(companyPhoto);
		}
		if (UtilValidate.isNotEmpty(company.getCompanyStatus())) {
			String companyStatus = company.getCompanyStatus();
			log.info("[[ 修改企业状态 ]] --- 将 id:"+company.getCompanyId()+" 的企业状态改为 "+ companyStatus);
			log.info("[[ 修改企业状态 ]] --- 修改企业对应的用户状态");
			User user = new User();
			user.setUserId(company.getCompanyId());
			user.setAccountStatus(companyStatus);
			userService.saveOrUpdate(user);

			log.info("[[ 修改企业状态 ]] --- 修改旗下的人事状态");
			QueryWrapper<Hr> wrapper = new QueryWrapper<>();
			wrapper.eq("company_id", company.getCompanyId());
			List<Hr> list = hrService.list(wrapper);
//			log.info("======"+list+". =="+companyStatus);
			hrService.updateHrList(list, companyStatus);
		}
		return companyMapper.updateById(company);
	}

	/**
	 * 删除企业
	 * @param companyId 企业编号
	 * @return 影响行数
	 */
	@Override
	@Transactional(rollbackFor = {DBOptionException.class, RuntimeException.class, Exception.class})
	public int deleteCompany(Long companyId) {
		if (UtilValidate.isEmpty(companyId)){
			return -1;
		}

		log.info("[[ 删除停止运营的企业 ]] --- 将 id:"+companyId+" 的企业删除");
		int deleteCompany = companyMapper.deleteById(companyId);

		log.info("[[ 删除停止运营的企业 ]] --- 将 User 账号删除");
		userService.removeById(companyId);

		log.info("[[ 删除停止运营的企业 ]] --- 将旗下的人事账号删除");
		QueryWrapper<Hr> wrapper = new QueryWrapper<>();
		wrapper.eq("company_id", companyId);
		hrService.remove(wrapper);

		return deleteCompany;
	}

	/**
	 * 分页查询收藏的企业信息
	 * @param currentPage 当前页
	 * @param pageSize 页大小
	 * @param searchValue 筛选条件
	 * @param followedList 收藏的企业 ID 列表
	 * @return
	 */
	@Override
	public Result getFollowCompanyInfoList(Integer currentPage, Integer pageSize,
	                                    String searchValue,  List<String> followedList){
		QueryWrapper<Company> wrapper = new QueryWrapper<>();
		wrapper.in("company_id", followedList);

		if (UtilValidate.isNotEmpty(searchValue)) {
			wrapper.and(w -> w.like("company_name", searchValue).
					or().like("company_address", searchValue).
					or().like("enterprises_type", searchValue));
		}

		Page<Company> companyPage = null;
		if (UtilValidate.isNotEmpty(pageSize)) {
			companyPage = new Page<>(currentPage, pageSize);
		}else {
			companyPage = new Page<>(currentPage, Constants.getPageSize());
		}
		IPage<Company> companyIPage = companyMapper.selectPage(companyPage, wrapper);
		return Result.succeed(companyIPage, "查询收藏的企业信息成功");
	}

	@Override
	public Result countCompany() {
		Integer integer = companyMapper.selectCount(null);
		if (UtilValidate.isNotEmpty(integer)) {
			return Result.succeed(integer, "查询成功");
		}else {
			return Result.failed("查询失败");
		}
	}
}
